package com.sdy.kzyy.web.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sdy.common.model.BizException;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.DateUtil;
import com.sdy.common.utils.StringUtil;
import com.sdy.kzyy.biz.model.KeyValueConfigurations;
import com.sdy.kzyy.biz.model.OrderRecord;
import com.sdy.kzyy.biz.service.KeyValueConfigurationsService;
import com.sdy.kzyy.biz.service.OrderRecordService;
import com.sdy.mvc.annotation.TaskSync;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 每天0点修改当天过期的订单状态为已过期
 *
 * @author Glm
 */
@Slf4j
@Component
public class OverdueOrderTask {
    @Autowired
    private OrderRecordService orderRecordService;
    @Autowired
    private KeyValueConfigurationsService keyValueConfigurationsService;

    @Scheduled(cron = "0 01 0 * * ? ")
    @TaskSync
    public void overdueOrderTask() throws BizException {
        Integer overdueDate = Integer.valueOf(keyValueConfigurationsService.getOverdueDate());
        // 获取所有未领取的有效订单
        List<OrderRecord> allValidOrderList = orderRecordService.list(new LambdaQueryWrapper<OrderRecord>().eq(OrderRecord::getReceiveStatus, 1).eq(OrderRecord::getOrderStatus, 2));
        // 获取当前日期
        String dateToDay = DateUtil.getDate(new Date(), "yyyyMMdd");
        List<OrderRecord> overdueOrderList = new ArrayList<>();
        // 循环获取在固定日期未领取的有效订单
        for (OrderRecord oneOrder : allValidOrderList) {
            if (oneOrder.getOrderTime() != null) {
                Date overdueTime = DateUtil.addDate(oneOrder.getOrderTime(), overdueDate+1);
                String overDueTimeString = DateUtil.getDate(overdueTime, "yyyyMMdd");
                // 如果订单的过期时间是今天，则加入需要修改的订单列表
                if (StringUtil.isNotBlank(overDueTimeString) && StringUtil.isNotBlank(dateToDay) &&
                        (Integer.valueOf(dateToDay) >= Integer.valueOf(overDueTimeString))) {
                    overdueOrderList.add(oneOrder);
                }
            }
        }
        // 将过期的订单状态修改为已过期
        if (!overdueOrderList.isEmpty()) {
            List<Integer> collect = overdueOrderList.stream().map(OrderRecord::getId).collect(Collectors.toList());
            boolean b = orderRecordService.update(Wrappers.<OrderRecord>lambdaUpdate().set(OrderRecord::getOrderStatus, 1).in(OrderRecord::getId, collect));
            Assert.notTrue(b, "修改过期订单状态失败");
        }
    }
}


